package com.aa.base.event

import androidx.lifecycle.LiveData

/**
 * @author Afra55
 * @date 2020/4/9
 * A smile is the best business card.
 */
object EventLiveData :LiveData<EventMessage?>(){

    const val EVENT_PERMISSION_RESULT = "BASE_EVENT_PERMISSION_RESULT"

    fun sendEvent(type: String, vararg any: Any) {
        val dataList = arrayListOf<Any>()
        for (v in any) {
            dataList.add(v)
        }
        value = EventMessage(type, dataList)
        emptyValue()
    }

    fun stickEvent(type: String, vararg any: Any) {
        val dataList = arrayListOf<Any>()
        for (v in any) {
            dataList.add(v)
        }
        value = EventMessage(type, dataList)
    }

    fun emptyValue() {
        value = null
    }


    fun sendError(type: String, errorCode: Int, errorMessage: String, errorObject: Any? = null) {
        value = EventMessage(
            type,
            arrayListOf(
                EventError(
                    errorCode,
                    errorMessage,
                    errorObject
                )
            )
        )
        emptyValue()
    }

}


/**
 * @author Afra55
 * @date 2019-06-20
 * A smile is the best business card.
 */
class EventMessage(var type:String, var listAny:ArrayList<Any>? ){
    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): EventMessage? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            this
        }
    }

    fun getDefaultObj(): Any? {
        if (listAny == null || listAny!!.isEmpty()) {
            return null
        }
        return listAny!![0]
    }

    override fun toString(): String {
        return "EventMessage(type=$type, listAny=$listAny)"
    }


}

data class EventError(val errCode:Int, val errMsg:String, var errorObj:Any? = null)